<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var obj = {
        name: "AAA",
        hobby: ["学习", "敲代码", "打球"],
        attr: {
          color: true,
          data: {
            age: 18,
          },
          has: null,
          active: undefined,
        },
        fun: function () {
          console.log("fun");
        },
      };
      //方法一
      // JSON 拷贝   函数和undefined 拷贝不了
      // let new_obj = JSON.parse(JSON.stringify(obj));

      //方法二
      //dest ==  目标对象或者数组，ori == 源对象或者数组
      function deep(dest, ori) {
        for (let key in ori) {
          //判断对象属性或者数组的值 是否 为 引用类型(Object, Array)
          if (typeof ori[key] == "object") {
            //递归 判断数组 还是对象
            dest[key] = ori[key].constructor === Array ? [] : {};
            deep(dest[key], ori[key]);
          } else {
            //非引用类型(string,number,bolear) 直接 把值添加到目标对象中
            dest[key] = ori[key];
          }
        }
        return dest;
      }
      let new_obj = deep({}, obj);

      new_obj.name = "BBB";
      new_obj.attr.color = false;
      new_obj.fun = function () {
        console.log("new_obj");
      };

      console.log(obj);
      console.log(new_obj);
      obj.fun();
      new_obj.fun();

      // 方法三
      // 函数和 拷贝不了
      const copyObj = structuredClone(obj);
    </script>
  </body>
</html>
